package com.googlecode.tracey.headers.http;

import com.googlecode.tracey.id.TraceyId;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import static com.googlecode.tracey.headers.Headers.TRACEY_ID_HEADER_NAME;
import static com.googlecode.tracey.id.TraceyIdValue.traceyIdValue;

public class TraceyIdStoringFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        TraceyId.set(traceyIdValue(request.getHeader(TRACEY_ID_HEADER_NAME)));
        if (!TraceyId.hasValue()) {
            TraceyId.makeOneUp();
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    public void destroy() {
    }
}
